package cn.rengy.web.framework.shiro.realm;

import java.security.Principal;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.rengy.web.framework.jwt.JwtService;
import cn.rengy.web.framework.principal.Identity;
import cn.rengy.web.framework.shiro.token.JwtToken;
import io.jsonwebtoken.ExpiredJwtException;

/**
 * jwt登录
 * @author rengy
 *
 */
@Component
public class JwtRealm extends IAuthorizingRealm{
	private static Logger logger = LoggerFactory.getLogger(JwtRealm.class);
	public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (!(authenticationToken instanceof JwtToken)) {
        	logger.error("error token {}",authenticationToken.getClass().getName());
            throw new AuthenticationException("错误的token登陆");
        }
        //ExpiredCredentialsException 凭据已失效
        //IncorrectCredentialsException 凭据与主体不匹配
        JwtToken jwtToken = (JwtToken)authenticationToken;
        String jwt = (String)jwtToken.getJwt();
        Identity identity=null;
        try {
        	identity=JwtService.parseToken(jwt);
        }catch(ExpiredJwtException e) {
        	throw new AuthenticationException("token已过期");
        }
        //校验客户端ip和useragent
        if(!jwtToken.getClientId().equals(identity.getClientId())) {
        	throw new AuthenticationException("客户端ip已改变，请重新登录");
        }
        
        return new SimpleAuthenticationInfo(identity,jwt,this.getName());
    }
}
